package files_controller_with_factory;
import java.io.*;
import java.nio.*;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.channels.*;
import org.apache.log4j.Logger;

public class CopyCommandExecutor implements ICommandExecutor{
	
	private static final Logger logger = Logger.getLogger(CopyCommandExecutor.class);  
	private static final Logger cont_log = Logger.getLogger("control");

	public void execute(String string){
		String[] str_mas = string.split(" ");
		String source_path = str_mas[1];
		String dest_path = str_mas[2];
		String name = str_mas[3];
		String full_source_path = source_path.concat("\\").concat(name);
		File path_s = new File(full_source_path);
		String full_dest_path = dest_path.concat("\\").concat(name);
		File path_d = new File(full_dest_path);	
		 try {
			Copy(path_s, path_d);
			cont_log.info("Files from " + path_s + " have copied to " + path_d);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			cont_log.error("Error of copy", e);
		}	
		
	}
	
	private void Copy(File f1, File f2) throws IOException{
		if(f1.isDirectory()){
			f2.mkdir();
			String[] list = f1.list();
			for(int i=0; i<list.length; i++){
				Copy(new File(f1, list[i]), new File(f2, list[i]));
				}	
		}else{
			f2.createNewFile();
			FileChannel inputChannel = null;
			FileChannel outputChannel = null;
			try{
				inputChannel = new FileInputStream(f1).getChannel();
				outputChannel = new FileOutputStream(f2).getChannel();
				outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
				logger.info("Data from " + f1.toString() + " copied to " + f2.toString());
			}finally{
				inputChannel.close();
				outputChannel.close();
			}
		}						
	}

	private static CopyCommandExecutor instance;
	private CopyCommandExecutor(){			
	}
	public static ICommandExecutor getInstance(){
		if(instance==null){
			instance = new CopyCommandExecutor(); 
		}
		return instance;
	}
}
